<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="题干" prop="topicContent">
        <el-input
          v-model="queryParams.topicContent"
          placeholder="请输入题干"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问答类型" prop="topicType">
        <el-select v-model="queryParams.topicType" clearable @change="handleQuery">
          <el-option
            v-for="dict in sys_topic_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="versionNum">
        <el-select v-model="queryParams.versionNum" clearable @change="handleQuery">
          <el-option
            v-for="dict in sys_topic_version"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:topic:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:topic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:topic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:topic:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="" align="center" prop="id" v-if="true"/>-->
      <el-table-column label="问答类型" align="center" prop="topicType">
        <template #default="scope">
          <dict-tag :options="sys_topic_type" :value="scope.row.topicType" />
        </template>
      </el-table-column>
      <el-table-column label="版本" align="center" prop="versionNum">
        <template #default="scope">
          <dict-tag :options="sys_topic_version" :value="scope.row.versionNum" />
        </template>
      </el-table-column>
      <el-table-column label="题干" align="center" prop="topicContent" show-overflow-tooltip>
        <template #default="scope">
          {{scope.row.topicContent}}
          <!-- <dict-tag :options="sys_show_hide" :value="scope.row.status" /> -->
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_show_hide" :value="scope.row.status" />
        </template>
      </el-table-column>
<!--      <el-table-column label="答案，A,B 等,多选题答案用逗号分割 " align="center" prop="correct" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:topic:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:topic:remove']">删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="topicRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目类型">
          <el-radio-group @change="changeTopicType" v-model="form.topicType">
            <el-radio
              v-for="dict in sys_topic_type"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="topicContent">
          <el-input v-if="form.topicType == '101'" type="textarea" v-model="form.topicContent"  maxlength="255" show-word-limit/>
          <editor v-else v-model="form.topicContent" :min-height="80"/>
        </el-form-item>
        <el-form-item label="版本" prop="versionNum">
          <el-select v-model="form.versionNum" placeholder="请选择">
            <el-option
              v-for="dict in sys_topic_version"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否多选">
          <el-radio-group v-model="form.isMultiple">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.isMultiple == '1'" label="多选个数">
          <el-input-number v-model="form.multipleNum"  :min="1" :max="10" label="描述文字"></el-input-number>
        </el-form-item>


        <el-form-item label="选项：">
          <el-form-item :label="item.prefix" :key="item.prefix"  v-for="(item,index) in form.items"  label-width="50px" class="question-item-label">
            <el-input v-model="item.prefix"  style="width:50px;" />
            <el-input v-if="form.topicType == '101'" v-model="item.content"   @focus="inputClick(item,'content')"  class="question-item-content-input"/>
            <editor v-else v-model="item.content" :min-height="80" :editorImgUploader="`editor-img-uploader-${index+1}`" :quillEditorRef="`quillEditorRef${index+1}`" />
            <el-button type="danger" icon="Delete" @click="questionItemRemove(index,item.prefix)"></el-button>
          </el-form-item>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_show_hide"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="questionItemAdd">添加选项</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Topic">
import { listTopic, getTopic, delTopic, addTopic, updateTopic } from "@/api/business/topic";

const { proxy } = getCurrentInstance();
const {sys_show_hide,sys_topic_type,sys_topic_version} = proxy.useDict("sys_show_hide","sys_topic_type","sys_topic_version");
const topicList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topicType: undefined,
    topicContent: undefined,
    status: undefined,
    correct: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    topicType: [
      { required: true, message: "题目类型,1=单选题,2=多选题不能为空", trigger: "change" }
    ],
    versionNum: [
      { required: true, message: "版本不能为空", trigger: "change" }
    ],
    topicContent: [
      { required: true, message: "题目内容不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态，0=正常，1=停用不能为空", trigger: "change" }
    ],
    correct: [
      { required: true, message: "答案，A,B 等,多选题答案用逗号分割 不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询题目列表 */
function getList() {
  loading.value = true;
  listTopic(queryParams.value).then(response => {
    for(var i = 0;i<response.rows.length;i++){
      let richTextRegex = /<(p)(.*?)>/g;
      if(richTextRegex.test(response.rows[i].topicContent)){
        response.rows[i].topicContent = extractTextFromRichContent(response.rows[i].topicContent);
      }
    }
    topicList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function changeTopicType(){
  form.value.items =  [
    { prefix: 'A', content: '' },
    { prefix: 'B', content: '' },
    { prefix: 'C', content: '' },
    { prefix: 'D', content: '' }
  ]
}

function extractTextFromRichContent(richContent) {
  // 创建一个新的DOM解析器
  const parser = new DOMParser();
  // 解析富文本内容为文档对象
  const doc = parser.parseFromString(richContent, 'text/html');
  // 提取文本内容
  return doc.body.textContent || '';
}
// 添加选项方法
function questionItemAdd () {
  let items = form.value.items
  let newLastPrefix
  if (items.length > 0) {
    let last = items[items.length - 1]
    newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
  } else {
    newLastPrefix = 'A'
  }
  items.push({ id: null, prefix: newLastPrefix, content: '' })
}

function  inputClick (object, parameterName) {
  // this.richEditor.object = object
  // this.richEditor.parameterName = parameterName
  // this.richEditor.dialogVisible = true
}
function questionItemRemove (index,prefix) {
  console.log(prefix)
  if(form.value.correct == prefix){
    form.value.correct = "";
  }
  form.value.items.splice(index, 1)
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    items: [
      { prefix: 'A', content: '' },
      { prefix: 'B', content: '' },
      { prefix: 'C', content: '' },
      { prefix: 'D', content: '' }
    ],
    isMultiple: '0',
    multipleNum: 1,
    topicType: '1',
    topicContent: null,
    status: '0',
    correct: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("topicRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加题目";
  form.value.items = [
    { prefix: 'A', content: ' ' },
    { prefix: 'B', content: ' ' },
    { prefix: 'C', content: ' ' },
    { prefix: 'D', content: ' ' }
  ]
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getTopic(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改题目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["topicRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateTopic(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addTopic(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除题目编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delTopic(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/topic/export', {
    ...queryParams.value
  }, `topic_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
.question-item-label {
  margin-top: 10px;
  margin-bottom: 10px !important;
}
.question-item-content-input {
  margin-left: 8px;
  width: 60%;
}
</style>
